package com.example.springsecurity.aop;

import com.alibaba.fastjson.JSON;

import com.example.springsecurity.domain.LogInfo;
import com.example.springsecurity.service.LogInfoService;
import com.example.springsecurity.utils.iputil.AddressUtils;
import com.example.springsecurity.utils.iputil.IpUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @ClassName SystemLogAspect
 * @Description TODO   切面
 * @Author lvyongwei
 * @Date 2020-05-21 13:11
 **/
@Aspect
@Component
@SuppressWarnings("all")
public class SystemLogAspect {

    //注入Service用于把日志保存数据库，实际项目入库采用队列做异步
    @Autowired
    private LogInfoService logService;
    //本地异常日志记录对象

    private static final Logger logger = LoggerFactory.getLogger(SystemLogAspect.class);
    //Service层切点    （全限定类名）
    @Pointcut("@annotation(com.example.springsecurity.aop.SystemServiceLog)")
    public void serviceAspect(){
    }

    //Controller层切点
    @Pointcut("@annotation(com.example.springsecurity.aop.SystemControllerLog)")
    public void controllerAspect(){
    }


    /**
     * @Description  前置通知  用于拦截Controller层记录用户的操作
     */
    @Before("controllerAspect()")
    public void doBefore(JoinPoint joinPoint){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        /**
         * 获取请求的url
         */
        String requestUrl=request.getRequestURI();
        /**
         * 获取请求参数
         */
        String params = "";
        if (joinPoint.getArgs()!=null&&joinPoint.getArgs().length>0){
            for (int i = 0; i < joinPoint.getArgs().length; i++) {
                /**
                 * 将请求参数转为json字符串形式
                 */
                params+= JSON.toJSONString(joinPoint.getArgs()[i]+";");   //获取请求方法中的参数
            }
        }
        try {
            /**
             * 定义日志实体类
             */
            LogInfo log=new LogInfo();
            //添加日志描述
            log.setLogName(getControllerMethodDescription(joinPoint));
            //添加用户ip
            String ip= IpUtils.getIpAddr(request);
            log.setIp(ip);
            //添加用户地理位置
            log.setAddress(AddressUtils.getAddressByIp(ip));
            log.setRequestUrl(requestUrl);
            log.setMethodName(joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
            log.setObject(params);
            log.setMessage("操作成功");
            log.setLogDate(new Date());
            /**
             * 执行插入日志的方法
             */
            logService.insertLog(log);
            logger.debug("日志插入成功");
        }catch (Exception e){
            //记录本地异常日志
            logger.error("==前置通知异常==");
            logger.error("异常信息：{}",e.getMessage());
        }
    }

    /**
     * @Description  异常通知 用于拦截service层记录异常日志
     */
    @AfterThrowing(pointcut = "serviceAspect()",throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint,Throwable e){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        /**
         * 获取用户请求路径
         */
        String requestUrl=request.getRequestURI();
        /**
         * 获取请求参数
         */
        String params = "";
        if (joinPoint.getArgs()!=null&&joinPoint.getArgs().length>0){
            for (int i = 0; i < joinPoint.getArgs().length; i++) {
                params+= joinPoint.getArgs()[i]+";";
            }
        }
        try{
            /**
             * 定义日志实体类
             */
            LogInfo log=new LogInfo();
            //添加日志描述
            log.setLogName(getControllerMethodDescription(joinPoint));
            //添加用户ip
            String ip=IpUtils.getIpAddr(request);
            log.setIp(ip);
            //添加用户地理位置
            log.setAddress(AddressUtils.getAddressByIp(ip));
            log.setRequestUrl(requestUrl);
            log.setMethodName(joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
            log.setObject(params);
            log.setMessage("操作成功");
            log.setLogDate(new Date());
            /**
             * 执行插入日志的方法
             */
            logService.insertLog(log);
            logger.debug("日志插入成功");
        }catch (Exception ex){
            //记录本地异常日志
            logger.error("==异常通知异常==");
            logger.error("异常信息:{}", ex.getMessage());
        }
    }


    /**
     * @Description  获取注解中对方法的描述信息 用于service层注解
     */
    public static String getServiceMethodDescription(JoinPoint joinPoint)throws Exception{
        //获取到当前注解的全限定类名
        String targetName = joinPoint.getTarget().getClass().getName();
        //获取到使用注解的方法名
        String methodName = joinPoint.getSignature().getName();
        //获取到使用注解的所有的参数
        Object[] arguments = joinPoint.getArgs();
        //使用反射
        Class targetClass = Class.forName(targetName);
        //获取到所有的方法
        Method[] methods = targetClass.getMethods();
        String description = "";
        for (Method method:methods) {
            //判断类中的方法与注解的方法同名时
            if (method.getName().equals(methodName)){
                Class[] clazzs = method.getParameterTypes();
                //比较参数的个数
                if (clazzs.length==arguments.length){
                    description = method.getAnnotation(SystemServiceLog.class).description();
                    break;
                }
            }
        }
        return description;
    }



    /**
     * @Description  获取注解中对方法的描述信息 用于Controller层注解
     */
    public static String getControllerMethodDescription(JoinPoint joinPoint) throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();//目标方法名
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String description = "";
        for (Method method:methods) {
            if (method.getName().equals(methodName)){
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length==arguments.length){
                    description = method.getAnnotation(SystemControllerLog.class).description();
                    break;
                }
            }
        }
        return description;
    }
}
